
package de.uni.wuppertal.server.ftp;

import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

import de.uni.wuppertal.server.ErrorLogEntry;
import de.uni.wuppertal.server.ui.MainWindow;

/**
 * @author Martin Schröder
 * @author Patrik Nordsiek
 */
public class FTPServerConnector extends Thread
{
	private FTPServer server;
	private int port;
	private FTPServerDataConnection connection;
	private boolean terminate = false;
	
	public FTPServerConnector(FTPServer server, int port)
	{
		super();
		
		this.server = server;
		this.port = port;
		
		setDaemon(true);
	}
	
	public int getPort()
	{
		return port;
	}
	
	public FTPServerDataConnection getConnection()
	{
		return connection;
	}
	
	public boolean isConnected()
	{
		return connection != null;
	}
	
	public void setTerminate(boolean terminate)
	{
		this.terminate = terminate;
	}
	
	public void close()
	{
		if(connection != null)
		{
			try
			{
				connection.close();
			}
			catch(Throwable t)
			{
				MainWindow.getInstance().log(new ErrorLogEntry(t));
			}
			
			connection = null;
		}
	}
	
	@Override
	public void run()
	{
		try
		{
			ServerSocket serverSocket = new ServerSocket(port);
			serverSocket.setSoTimeout(100);
			
			while(true)
			{
				try
				{
					Socket clientSocket = serverSocket.accept();
					
					serverSocket.close();
					
					connection = new FTPServerDataConnection(server, clientSocket);
					
					break;
				}
				catch(SocketTimeoutException e)
				{
					if(terminate)
					{
						if(connection != null)
						{
							connection.close();
							connection = null;
						}
						
						break;
					}
				}
			}
		}
		catch(Throwable e)
		{
			if(connection != null)
			{
				try
				{
					connection.close();
				}
				catch(Throwable t)
				{
					MainWindow.getInstance().log(new ErrorLogEntry(t));
				}
				
				connection = null;
			}
		}
	}
}
